import { MailerService } from '@nestjs-modules/mailer';
import { Injectable, Logger } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
import { User } from 'src/database/entitys/user.entity';
import { UserService } from 'src/modules/system/user/user.service';

@Injectable()
export class EmailService {
  private codes = new Map<string, string>();

  constructor(
    private mailerService: MailerService,
    private userService: UserService
  ) {}

  /**
   * 发送验证码
   * @param email
   * @returns
   */
  async sendVerificationCode(email: string): Promise<String | null> {
    const user = await this.userService.findByEmail(email);
    if (!user) {
      return null;
    }
    const code = uuidv4().slice(0, 4);
    this.codes.set(email, code);

    await this.mailerService.sendMail({
      to: email,
      subject: '小橘子决策系统 - 登录验证码',
      text: `您好，您的验证码是:【${code}】`,
    });

    return '发送成功';
  }

  /**
   * 验证验证码
   * @param email
   * @param code
   * @returns
   */
  async verifyCode(email: string, code: string): Promise<User | null> {
    const savedCode = this.codes.get(email);

    if (savedCode === code) {
      this.codes.delete(email);
      return await this.userService.findByEmail(email);
    }
    return null;
  }
}
